package com.hengby.hengcrud.modular.job.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hengby.hengcrud.core.util.SpringContextHold;
import com.hengby.hengcrud.modular.job.mapper.JobMapper;
import com.hengby.hengcrud.modular.job.model.Job;
import com.hengby.hengcrud.modular.job.service.JobService;
import com.hengby.hengcrud.modular.job.util.ScheduleUtils;
import org.quartz.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhouheng
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JobServiceImpl extends ServiceImpl<JobMapper,Job> implements JobService {

    private JobMapper jobMapper = SpringContextHold.getBean(JobMapper.class);

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init() {
		List<Job> scheduleJobList = jobMapper.selectList(new EntityWrapper<>());
		for (Job scheduleJob : scheduleJobList) {
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduleJob.getJobId());
			// 如果不存在，则创建
			if (cronTrigger == null) {
				ScheduleUtils.createScheduleJob( scheduleJob);
			} else {
				ScheduleUtils.updateScheduleJob(scheduleJob);
			}
		}
	}

	@Override
	public Job findJob(Long jobId) {
		return this.baseMapper.selectJobById(jobId);
	}

	@Override
	public List<Job> findAllJobs(Job job) {
		/*try {
			Example example = new Example(Job.class);
			Criteria criteria = example.createCriteria();
			if (StringUtils.isNotBlank(job.getBeanName())) {
				criteria.andCondition("bean_name=", job.getBeanName());
			}
			if (StringUtils.isNotBlank(job.getMethodName())) {
				criteria.andCondition("method_name=", job.getMethodName());
			}
			if (StringUtils.isNotBlank(job.getStatus())) {
				criteria.andCondition("status=", Long.valueOf(job.getStatus()));
			}
			example.setOrderByClause("job_id");
			return this.selectByExample(example);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return new ArrayList<>();
		}*/

		return null;
	}

	@Override
//	@Transactional
	public void addJob(Job job) {
		job.setCreateTime(new Date());
		job.setStatus(Job.ScheduleStatus.PAUSE.getValue());

		this.baseMapper.insert(job);
		ScheduleUtils.createScheduleJob(job);
	}

	@Override
	@Transactional
	public void updateJob(Job job) {
		ScheduleUtils.updateScheduleJob(job);
		this.baseMapper.updateNotNull(job);
	}

	@Override
	@Transactional
	public void deleteBatch(String jobIds) {
		List<String> list = Arrays.asList(jobIds.split(","));
		for (String jobId : list) {
			ScheduleUtils.deleteScheduleJob(Long.valueOf(jobId));
		}
		this.baseMapper.batchDelete(list, "jobId", Job.class);
	}

	@Override
	@Transactional
	public int updateBatch(String jobIds, String status) {
		List<String> list = Arrays.asList(jobIds.split(","));

        Job job = new Job();
        job.setStatus(status);
        Wrapper<Job> wrapper = new EntityWrapper<>();
        wrapper.in("status",list);

        // 修改job状态
        this.baseMapper.update(job,wrapper);

		return 1;
	}

	@Override
	@Transactional
	public void run(String jobIds) {
		String[] list = jobIds.split(",");
		for (String jobId : list) {
            Job job = this.baseMapper.selectJobById(Long.parseLong(jobId));
            job.setStatus(Job.ScheduleStatus.NORMAL.getValue());
            Wrapper<Job> wrapper = new EntityWrapper<>();
            wrapper.eq("job_id", Long.parseLong(jobId));

            ScheduleUtils.run(job);

            // 修改job状态
            this.baseMapper.update(job,wrapper);
		}
	}

	@Override
	@Transactional
	public void pause(String jobIds) {
		String[] list = jobIds.split(",");
		for (String jobId : list) {
            Job job = this.baseMapper.selectJobById(Long.parseLong(jobId));
            job.setStatus(Job.ScheduleStatus.PAUSE.getValue());
            Wrapper<Job> wrapper = new EntityWrapper<>();
            wrapper.eq("job_id", Long.parseLong(jobId));

            ScheduleUtils.pauseJob(Long.valueOf(jobId));

            // 修改job状态
            this.baseMapper.update(job,wrapper);
		}
	}

	@Override
	@Transactional
	public void resume(String jobIds) {
		String[] list = jobIds.split(",");
		for (String jobId : list) {
			ScheduleUtils.resumeJob(Long.valueOf(jobId));
		}
		this.updateBatch(jobIds, Job.ScheduleStatus.NORMAL.getValue());
	}

    @Override
    public List<Map<String, Object>> list(String name, String methodName) {
        return this.baseMapper.selectJobs(name,methodName);
    }
}
